import re
import random
import socket
import urllib
import urllib2

from django.core.management.base import BaseCommand

from mobile.models import CAPVPuertoIncident, CAPVPuertoCapture

class Command(BaseCommand):
    help = "Sniff CAPV Puertos"
    
    requires_model_validation = True
    
    def handle(self, *app_labels, **options):
        #Get site
        ff_version = "%s.%s.%s.%s" % tuple([random.randint(0,3) for i in range(4)])
        user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.4) Gecko/20070515 Firefox/%s" % ff_version #CAPV no te enfades con Firefox
        url = "http://www.trafikoa.net/public/wps/portal/trafico/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLd4s3cjcHSZnFO8ZbeulHogt5IoR8PfJzU_WD9L31A_QLckMjyh0dFQEAU64A/delta/base64xml/L3dJdyEvd0ZNQUFzQUMvNElVRS82X0ZfMkc1"
        headers = { 'User-Agent' : user_agent }
        socket.setdefaulttimeout(10)
        req = urllib2.Request(url, None, headers)
        response = urllib2.urlopen(req)
        data = response.read()
    
        #Generamos una captura
        capture = CAPVPuertoCapture()
        capture.save()
        
        #Process
        data = data.split(r'function mostrarPuertos() {')[1].split('}')[0].split('\n')
        for incidencia in data:
            if incidencia != "":
                try:
                    args = re.sub(r'^generarPuntoPuerto\((.*)\)$',r'\1', incidencia).split(',')
                    args = [a.strip()[1:-1] for a in args]
                
                    puerto = CAPVPuertoIncident()
                    puerto.capture = capture
                    puerto.set_data(*args)
                    puerto.save()
                except:
                    raise
                    pass
                    
        #Activamos la captura
        capture.finished = True
        capture.save()
                